import { get, save, remove, LOCAL, SESSION } from '$ui/utils/storage';

// 登录信息保存到 sessionStorage 的key
const USER_CACHE_KEY = 'USER_INFO';
const USER_TOKEN = 'TOKEN';
const TOKEN_KEY = 'TOKEN';
const PERMS_KEY = 'PERMS'

export function savePermsToCache(perms) {
  save(PERMS_KEY, perms, LOCAL)
}

export function getPermsToCache() {
  return get(PERMS_KEY, LOCAL)
}

export function removePermsToCache() {
  remove(PERMS_KEY, LOCAL)
}
/**
 * 从sessionStorage获取用户信息
 * @returns {*}
 */
export function getUserFromCache() {
  return get(USER_CACHE_KEY, LOCAL);
}

/**
 * 写入用户信息到 sessionStorage
 * @param {Object} user
 */
export function saveUserToCache(user) {
  save(USER_CACHE_KEY, user, LOCAL);
}

/**
 * 清除sessionStorage用户信息
 * @param {Object} user
 */
export function removeUserToCache(user) {
  remove(USER_CACHE_KEY, LOCAL);
  removeToken();
  removePermsToCache()
}

export function saveTokenToLocal(token) {
  save(USER_TOKEN, token, LOCAL);
}

export function getTokenFromLocal() {
  return get(USER_TOKEN, LOCAL);
}

export function saveTokenToSession() {
  const token = getTokenFromLocal();
  save(USER_TOKEN, token, SESSION);
}

export function getTokenFromSession() {
  return get(USER_TOKEN, SESSION);
}

export function removeToken() {
  remove(USER_TOKEN, LOCAL);
  remove(USER_TOKEN, SESSION);
}

export function isDiffentUser() {
  const localToken = getTokenFromLocal();
  const sessionToken = getTokenFromSession();
  return localToken !== sessionToken;
}

/**
 * 获取用户信息
 * @param type 分为local,session
 * @returns {*}
 */
export function getTokenFromCache(type = '') {
  const cacheType = type === 'local' ? LOCAL : SESSION
  return get(TOKEN_KEY, cacheType)
}

/**
 * 写入用户信息
 * @param token
 * @param type 分为local,session
 */
export function saveTokenToCache(token, type = '') {
  const cacheType = type === 'local' ? LOCAL : SESSION
  save(TOKEN_KEY, token, cacheType)
}

/**
 * 清除用户信息
 * @param type 分为local,session
 */
export function removeTokenFromCache(type = '') {
  const cacheType = type === 'local' ? LOCAL : SESSION
  remove(TOKEN_KEY, cacheType)
}

/**
 * 退出登录
 */
export function logout() {
  // const token = getTokenFromCache()
  // oauth2Logout({token}).then(_ => {
  //   removeTokenFromCache()
  //   removeUserToCache()
  //   setTimeout(() => {
  //     window.location.reload()
  //   }, 100)
  // })
}

/**
 *
 * @param menuCode
 * @returns {T}
 */
export function getMenuByMenuCode(menuCode) {
  const user = getUserFromCache() || {}
  const menus = user.menus || []
  return menus.find(item => item.menuCode === menuCode)
}
